﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Casamiel.Application;
using Casamiel.Common;
using Casamiel.Domain;
using MediatR;

namespace Casamiel.API.Application.Commands
{
	/// <summary>
	/// 
	/// </summary>
	public sealed class LogoutCommandHandler : IRequestHandler<LogoutCommand, bool>
	{

		private readonly IMemberService _memberService;
		private readonly IUserLogService _userLogService;
		
		/// <summary>
		/// 
		/// </summary>
		/// <param name="memberService"></param>
		/// <param name="userLogService"></param>
		public LogoutCommandHandler(IMemberService memberService,IUserLogService userLogService)
		{
			_memberService = memberService;
			_userLogService = userLogService;
		}
		/// <summary>
		/// 
		/// </summary>
		/// <param name="request"></param>
		/// <param name="cancellationToken"></param>
		/// <returns></returns>
		public async Task<bool> Handle(LogoutCommand request, CancellationToken cancellationToken)
		{
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            var mtoken = await _memberService.FindAsync<ICasaMielSession>(request.Mobile, request.LoginType).ConfigureAwait(false);
			if (mtoken != null)
			{
				mtoken.Access_Token = "";
				await _memberService.UpdateAsync<ICasaMielSession>(mtoken).ConfigureAwait(false);
			}
			//string key = Constant.TOKEN_PREFIX + request.Mobile + "_" + request.LoginType;
			//_cacheService.Remove(key);
			var OPinfo = "注销";
			if (request.LoginType == 4)
			{
				OPinfo = "员工注销";
			}
			var logdata = new UserLog { Url = request.RequestUrl, OPInfo = OPinfo, OPTime = DateTime.Now, UserName = request.Mobile, UserIP =request.UserIP };
			await _userLogService.AddAsync<ICasaMielSession>(logdata).ConfigureAwait(false);
			return true;
		}
	}
}
